<?php
namespace Home\Controller;
use Think\Model;
use Think\Controller;
class UserController extends Controller {
    public function index(){
        if(!session('home_uid')){
            $this->error('请先登录',U('Login/index'));
        }
        $user_one = M('user')->find(session('home_uid'));
        $this->assign('user_one',$user_one);
        $this->assign('user_menu',$this->getUserMenu());
        $this->assign('orders_count_arr',$this->getOrderStatusCountArr());
        $this->display();
    }

    /**
     * 获取默认地址信息
     * @param int $id
     * @return string 地址字符串
     */
    protected function getDefaultAddr($id = 0){
        $addr_word = '';
        if($id > 0){
            $one = M('address')->find($id);
            if($one){
                $addr_word = $one['prov'] . $one['city'] . $one['dist'] . $one['address'] . " 收货人手机："
                    . $one['mobile'] . "收货人姓名:" . $one['username'];
            }else{
                return $addr_word;
            }
        }
        return $addr_word;
    }





    /**
     * 修改地址
     * @param $id
     */
    public function change_addr(){
        if(IS_POST){
//            var_dump(I('post.'));
            $data = I('post.');

            $Address = D('Address');
            $Address->setData($data);
            $res = $Address->updateDb();
            if($res !== false){
                $this->success('修改成功',U('add_address'));
            }else{
                $this->error('修改失败');
            }
        }
    }

    public function del_addr($id = 0){
        if($id < 1){
            $this->error("非法操作");
        }

        $res = M('Address')->delete($id);
        if($res !== false){
//           如果删除的地址是默认地址，那么设置会员的默认地址id为0
            $wh['id'] = session('home_uid');
            $wh['address_id']= $id;
            $one = M('User')->where($wh)->find();

            if($one){
                $data['id'] = session('home_uid');;
                $data['address_id'] = 0;
                $data['u_time'] = time();
                $res1 = M('User')->data($data)->save();
            }
            $this->success('删除成功',U('add_address'));
        }else{
            $this->error('删除失败：',U('add_address'));
        }
    }


    /**
     * 获取待收货，待发货，待收货订单的数量
     * @return array
     */
    protected function getOrderStatusCountArr(){
        //需要条件，状态值 和 用户id
        $wait_pay_orders = M('Order')->distinct(true)->field('order_id')->where(array('status'=>array('in','1,2'),'user_id'=>session('home_uid')))->select();
        $wait_deliver_orders = M('Order')->distinct(true)->field('order_id')->where(array('status'=>array('in','3'),'user_id'=>session('home_uid')))->select();
        $wait_take_orders = M('Order')->distinct(true)->field('order_id')->where(array('status'=>array('in','4'),'user_id'=>session('home_uid')))->select();
        $wait_get_orders = M('Order')->distinct(true)->field('order_id')->where(array('status'=>array('in','5'),'user_id'=>session('home_uid')))->select();
        $orders_count = array(
            count($wait_pay_orders),
            count($wait_deliver_orders),
            count($wait_take_orders),
            count($wait_get_orders)
        );
        return $orders_count;
    }

    /**
     *
     */
    public function cart(){
        $this->return_number();

        $wh['user_id'] = session('home_uid');//uid
        $wh['status']  = 0; //订单状态
        //查找  用户购物车的商品

        $order = M('Order')
                    ->alias('o')
                    ->field('o.id,o.goods_id,o.shop_price,o.attr,o.color,o.num,g.title,g.img,g.shop_price as goods_shop_price,g.attr as goods_attr')
                    ->where($wh)
                    ->join('__GOODS__ as g on g.id = o.goods_id','left')
                    ->select();
        $this->assign('order',$order);
        $this->display('cart');
    }

    /**
     * @param $id删除购物车商品
     */
    public function delect_cart_goods($id){
        $wh['user_id'] = session('home_uid');
        $wh['status']  = 0; //订单状态
        $wh['id']     = $id;
        
        //不报错了
        M('Order')->where($wh)->delete();

        $wh['user_id'] = session('home_uid');//uid
        $wh['status']  = 0; //订单状态
        //查找  用户购物车的商品
        $this->cart();
    }

    /**
     * @param int $id   框选的商品的ID
     * @param int $number 商品的数量
     */
    public function checkout($id = 0,$number = 0){

        if(!$number || !$id){
            $this->error('至少选择一件商品购买');
        }
        $this->return_number();//返库存


        $wh['user_id'] = session('home_uid');
        $address = M('address')->where($wh)->select();
        if(!$address){//查找有没有默认地址
//            dump(I('server.REQUEST_URI'));
            cookie('checkout',str_replace('&amp;', '&',I('server.REQUEST_URI')),array('expire'=>3600*7*24,'prefix'=>'lh_'));
            //重定向到New模块的Category操作
            $this->redirect('User/add_address');
        }else{
            $wh = array();
            $wh['user_id'] = session('home_uid');
            $address_list = M('address')->where($wh)->select();
            $one = M('User')->field('address_id')->find(session('home_uid'));

            $wh = array();
            $wh['user_id'] = session('home_uid');
            $wh['status'] = 0;
            if(is_array(I('get.id'))){
                $wh['o.id'] = array('in',implode(',', I('get.id')));//in (1,3)
                $number = I('get.number');
//                var_dump($wh);
//                var_dump($number);
//                exit;
            }else{
                $wh['o.id'] = I('get.id');
                $number = array($wh['o.id']=>I('get.number'));
            }

//            var_dump($number);
            $order = M('Order')
                ->alias('o')
                ->field('o.id,o.goods_id,o.attr,o.color,o.num,g.title,g.img,g.shop_price as goods_shop_price,g.attr as goods_attr')
                ->where($wh)
                ->join('__GOODS__ as g on g.id = o.goods_id','left')
                ->select();
//            var_dump($order);
            $this->assign('order',$order);  //订单
            $this->assign('default_id',$one['address_id']);//默认地址
            $this->assign('number',$number);  //数量
            $this->assign('address_list',$address_list);//地址李彪
            $this->display();
        }

    }

    public function set_default_addr(){
        $wh['id'] =   session('home_uid');
        $wh['address_id'] = I('post.id');
        $res = M('User')->data($wh)->save();
        if($res !== false){
            $this->success('修改成功',U('index'));
        }else{
            $this->error('修改失败 '.M('User')->getError());
        }
        $this->redirect('add_address');
    }

    /**
     * 添加收货地址界面
     */
    public function add_address(){
        $wh = array();
        $wh['user_id'] = session('home_uid');
        $address_list = M('address')->where($wh)->select();

        $one = M('User')->field('address_id')->find(session('home_uid'));


        if(IS_POST){
            $address = D('address');
            $data = I('post.');
            $data['user_id'] = session('home_uid');
            $address->setData($data);
            $res = $address->insertDb();
            if($res){
                if(cookie('lh_checkout')){
                    $url = cookie('lh_checkout');
                }else{
                    $url = U('index');
                }
                $this->success('添加成功',$url);
            }else{
                $this->error('添加失败'.$address->getError());
            }
            exit;
        }else{
            $this->assign('default_id',$one['address_id']);
            $this->assign('address_list',$address_list);
            $this->display('add_address');
        }
    }

    public function done(){
        if(IS_POST){
//            var_dump("have post");
//            var_dump(I());
            $id     = I('post.id');       //商品id 多个为数组
            $number = I('post.number');  //数量 多个为数组
            $address_id = I('post.address_id'); //收货地址
            if(!$number || !$id || !$address_id){//缺一不可
                $this->error('参数错误');
            }

            $model = new Model();
            $model->startTrans();//开启事务

            //订单的公共数据
            $data['status']  = 1;
            $wh['status']    = 0;
            $data['user_id'] = $wh['user_id']=session('home_uid');
            $data['u_time'] = time();
            $data['address_id'] = $address_id;
            $data['order_id'] = getRandOrder();

//            var_dump($data['order_id']);16位
            foreach($id as $k =>  $v){
                $data['id'] = $wh['o.id'] = $v;
                //查找商品id价格
                $order = $model->table('__ORDER__')
                    ->alias('o')
                    ->field('g.shop_price')
                    ->where($wh)
                    ->join('__GOODS__ as g on g.id = o.goods_id','left')
                    ->find();

                if(!$order){
                    $model->rollback(); //有报错 回滚 操作 不更新订单信息
                    $this->error('结算失败，请刷新后再试1');
                }
                //订单的数量
                $data['num'] = $number[$k];
                //用刚刚查找数据库的价钱
                $data['shop_price'] = $order['shop_price'];

                $res = $model->table('__ORDER__')->data($data)->save();
                if($res === false ){
                    //其中一条购物车 生成订单失败 回滚
                    $model->rollback();
                    $this->error('结算失败,请刷新后再试2');
                }
            }
            $model->commit();//都成功提交数据库
            //重定向，传id
            $this->redirect('Home/User/done/id/'.$data['order_id']);
        }else{
            //通过订单id 查询订单数据并且输出，然后选择支付方式 支付
//            var_dump("no post");
//            var_dump(I('get.id'));
            $wh['order_id'] = I('get.id');
            if(!$wh['order_id']){
//                var_dump('参数错误');
                $this->error('参数错误');
            }
            $wh['status'] = array('in','1,2');//1为没有减库存的，2是减库存的
            $wh['user_id'] = session('home_uid');
            $order = M('Order')
                ->alias('o')
                ->field('o.attr,o.order_id,o.color,o.num,g.title,g.shop_price as goods_shop_price')
                ->where($wh)
                ->join('__GOODS__ as g on g.id = o.goods_id','left')
                ->select();
            $this->assign('order',$order);

            $this->display();
        }
    }


    public function pay(){
        $this->return_number();
        if(IS_POST){
            $wh['order_id'] = I('post.id');;
            if(!$wh['order_id']){
                $this->error('参数错误');
            }
            $wh['status'] = array('in','1,2');
            $wh['user_id'] = $data['user_id'] = session('home_uid');

            $order = M('order')
                ->alias('o')
                ->field('o.id,o.goods_id,o.attr,o.color,o.num,o.status,o.u_time,g.title,g.shop_price as goods_shop_price,g.attr as goods_attr')
                ->where($wh)
                ->join('__GOODS__ as g on g.id = o.goods_id','left')
                ->select();
            if(!$order){
                $this->error('参数错误');
            }
            if(!I('post.pay_type')){
                $data['status'] = 3;
            }else{
                $data['status'] = 2;
            }
            $data['u_time'] = time();

            $model = new Model();
            $model->startTrans();//开启事务;

            $data['pay_type'] = I('post.pay_type');
            $title = '';
            $body = '';
            $all_money = 0;
            foreach($order as $k => $v){
                //是否满足库存
                $goods_attr = json_decode($v['goods_attr'],true);
                $number = $goods_attr[$v['attr']];

                if($v['num'] > $number){
                    $model->rollback();
                    $this->error('【'.$v['title'].'-'.$v['color'].'-'.$v['attr'].'】库存不足，只剩下'.$number.'件，请重新购买',U('Goods/info',array('id'=>$v['goods_id'])));
                }
                //更新价格
                $data['shop_price'] = $v['goods_shop_price'];

                //商品表 统计要减的库存
                $goods[$v['goods_id']]['attr'][$v['attr']] = $v['num'];
                $goods[$v['goods_id']]['all_attr'] = $goods_attr;

                $data['id']=$v['id']; //商品id
                $res = $model->table('__ORDER__')->data($data)->save(); //对比goods表后,更新order表的信息
                if($res === false){
                    $model->rollback();//有报错 回滚 操作 不更新订单信息
                    $this->error('网络错误，请稍后在试');
                }
                //三维数组
                //                array (size=1)
                //                  35 =>
                //                    array (size=2)
                //                      'attr' =>
                //                        array (size=1)
                //                          'm' => string '1' (length=1)
                //                      'all_attr' =>
                //                        array (size=2)
                //                          'm' => int 2
                //                          's' => int 40
                if(!$title){
                    if(count($order)>1){
                        $oo = ' 等多件';
                    }else{
                        $oo = '';
                    }
                    $title = '【'.$v['title'].'-'.$v['color'].'-'.$v['attr'].'】'.$oo;
                    $show_url = 'http://'.I('server.HTTP_HOST').U('Goods/info',array('id'=>$v['goods_id']));

                }



                $body .= '【'.$v['title'].'-'.$v['color'].'-'.$v['attr'].'】 ';
                $all_money += $v['goods_shop_price'] * $v['num'];
                //            商品减库存
                // 0 购物车
                // 1 待支付没减库存
                // 2 待支付已减库存
                // 减库存条件:订单状态为1 或者 状态为2 但是 已超时
//            var_dump($v['status']);



            }

            if($v['status'] == 1 || ($v['status'] == 2 && time() - $v['u_time'] > 30 * 60)){
                foreach ($goods as $kk => $vv) {
                    $g['id'] = $kk;
                    $nn = 0;
                    foreach ($vv['attr'] as $kkk => $vvv) {
                        $nn += $vvv;
                        $vv['all_attr'][$kkk] -= $vvv;
                    }

                    // array('exp','score+1');// 用户的积分加1
                    $g['number'] = array('exp','number-'.$nn);// 减库存
                    $g['attr'] = json_encode($vv['all_attr']);



                    $res = $model->table('__GOODS__')->data($g)->save();
                    if($res === false){
                        $model->rollback();//有报错 回滚 操作 不更新库存
                        $this->error('网络错误，请稍后在试');
                    }
                }
            }
            $model->commit();//都成功提交数据库

            //结算完成
            if(!$data['pay_type']){
                //货到付款
                M('order')->data(array('status',3))->save();

                $this->success('付款成功，请耐心等待发货',U('index'));
            }else{
                //支付宝付款

                $alipay['order_id'] = $wh['order_id'];
                $alipay['title'] = $title;
                $alipay['all_money'] = $all_money;
                $alipay['body'] = $body;
                $alipay['show_url'] = $show_url;


                my_alipay($alipay);
            }
        }else{
            $this->error('参数错误');
        }
    }

    public function tb_return_url(){
        // var_dump(I());
        $alipay_config = C('ALIPAY_CONFIG');//获取 键名为ALIPAY_CONFIG的配置
        // require_once("lib/alipay_notify.class.php");
        vendor("alipay.lib.alipay_notify#class");
        //计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {
            //验证成功

            //商户订单号

            $wh['order_id'] = $_GET['out_trade_no'];

            //支付宝交易号

            $trade_no = $_GET['trade_no'];

            //交易状态
            $trade_status = $_GET['trade_status'];


            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                //订单状态已在异步通知中 改变了订单
                //没改变 就直接改
                $data['status'] = 3;
                $data['u_time'] = time();
                $res = M('Order')->where($wh)->data($data)->save();
                if($res !== false){
                    // var_dump('success');
                    // $this->success('购买成功，请耐心等待发货',U('Goods/index'),300);
                    $this->success('购买成功，请耐心等待发货',U('Goods/index'));
                }else{
                    $this->error('网络错误，请稍后在试',U('Goods/index'));
                }
            }else {
                $this->error('网络错误，请稍后在试',U('Goods/index'));
            }
        }
        else {
            //验证失败
            //如要调试，请看alipay_notify.php页面的verifyReturn函数
            $this->error('网络错误，请稍后在试',U('Goods/index'));
        }
    }


    // 返回库存 去支付宝 支付了 但是超时未支付 库存返回
    // 条件
    // 超时30分钟 $wh['u_time'] = array('lt',time() - 1800);
    // 订单状态 = 2 $wh['status'] = 2;
    // 支付方式为支付宝 $wh['pay_type'] = 1;
    private function return_number()
    {
        $wh['u_time'] = array('lt',time() - 0);
        $wh['status'] = 2;
        $wh['pay_type'] = 1;
        $data = M('Order')->where($wh)->select();
    }

    /**
     * @param $order  订单列表
     * @return array  整理后的订单列表
     */
    private function arrangeOrder($order){
        if(!$order){
            return $order;
        }
        foreach ($order as $v){
            $arr[] = $v['order_id'];
        }
        $uni_arr = array_unique($arr);
        $arr = array();
        foreach ($uni_arr as $v){
            $arr[$v] = array();
        }
       foreach ($order as $v){
           array_push($arr[$v['order_id']],$v);
       }
       return $arr;
    }

    /**
     * 待付款
     */
    public function wait_pay(){
        $this->return_number();

        $wh['user_id'] = session('home_uid');//uid
        $wh['status']  = array('in','1,2'); //订单状态
        //查找  待付款
        $order = M('Order')
            ->alias('o')
            ->field('o.order_id,o.id,o.goods_id,o.shop_price,o.attr,o.color,o.num,g.title,g.img,g.shop_price as goods_shop_price,g.attr as goods_attr')
            ->where($wh)
            ->join('__GOODS__ as g on g.id = o.goods_id','left')
            ->order('o.u_time desc')
            ->select();
        $new_order = $this->arrangeOrder($order);
//        var_dump($new_order);
        $this->assign('order',$new_order);
        $this->assign('user_menu',$this->getUserMenu());

        $this->display();
    }

    /**
     * 待发货
     */
    public function wait_deliver(){
        $this->return_number();
        $wh['user_id'] = session('home_uid');//uid
        $wh['status']  = 3; //订单状态
        //查找  待付款
        $order = M('Order')
            ->alias('o')
            ->field('o.order_id,o.id,o.goods_id,o.shop_price,o.attr,o.color,o.num,g.title,g.img,g.shop_price as goods_shop_price,g.attr as goods_attr')
            ->where($wh)
            ->join('__GOODS__ as g on g.id = o.goods_id','left')
            ->order('o.u_time desc')
            ->select();
        $new_order = $this->arrangeOrder($order);
        $this->assign('order',$new_order);
        $this->display();
    }

    /**
     * 待收货
     */
    public  function wait_take(){
        $this->return_number();
        $wh['user_id'] = session('home_uid');//uid
        $wh['status']  = 4; //订单状态
        //查找  待付款
        $order = M('Order')
            ->alias('o')
            ->field('o.order_id,o.id,o.goods_id,o.shop_price,o.attr,o.color,o.num,g.title,g.img,g.shop_price as goods_shop_price,g.attr as goods_attr')
            ->where($wh)
            ->join('__GOODS__ as g on g.id = o.goods_id','left')
            ->order('o.u_time desc')
            ->select();
        $new_order = $this->arrangeOrder($order);
        $this->assign('order',$new_order);
        $this->display();
    }

    protected  function  getUserMenu(){
        $data = M('menu')->order('sort asc,u_time desc,id desc')
            ->select();
        $data = get_category($data,USERMENU_PID);
        return $data;
    }

    /**
     * @return array 返回订单总量，和本页的5个订单
     */
    protected function getPageOrders($o_status){
        //最多5个订单一页
        $curPage = I('get.p',1);
        $orders = M('Order')
            ->distinct(true)
            ->field('order_id')
            ->where(array(
                'status'=>array('in',$o_status),
                'user_id'=>session('home_uid')
            ))//订单状态 和 uid
            ->order('u_time desc')
            ->select();
//        var_dump(count($orders));
        foreach ($orders as $v){
            if($v['order_id']){
                $arr[] = $v['order_id'];
            }
        }
        $temp  = array_unique($arr);
        $count = count($temp);
        $j = 0;
        $orders = array();
        foreach ($temp as $v){
            if($j >= 5 *$curPage){
                break;
            }else if( $j >= 5 * ($curPage-1)){
                $orders[] = $v;
            }
            $j++;
        }

        $res=array(
            'count'=>$count,
            'orders'=>$orders,
        );
        return $res;
    }

    /**
     *
     */
    public  function already_bought($o_status = '1,2,3,4,5'){
        $this->return_number();
        $wh['user_id'] = session('home_uid');//uid
        $wh['status']  = array('in',$o_status); //订单状态

        $pageArr = $this->getPageOrders($o_status);
//        var_dump($pageArr);
        $page = h_page($pageArr['count']);

        $wh['order_id']=array('in',implode(',',$pageArr['orders']));
        //查找
        $order = M('Order')
            ->alias('o')
            ->field('o.pay_type,o.status,o.order_id,o.id,o.goods_id,o.shop_price,o.attr,o.color,o.num,g.title,g.img,g.shop_price as goods_shop_price,g.attr as goods_attr')
            ->where($wh)
            ->join('__GOODS__ as g on g.id = o.goods_id','left')
            ->order('o.u_time desc')
            ->select();

        $new_order = $this->arrangeOrder($order);

        $this->assign('order',$new_order);
        $this->assign('page',$page);
        $this->assign('o_status',$o_status);
        $this->assign('user_menu',$this->getUserMenu());
        $this->assign('orders_count_arr',$this->getOrderStatusCountArr());
        $this->display();
    }


    public  function user_info(){
        if(IS_POST){
            $data = I('post.');
            $data['id'] = session('home_uid');

            $User = D('User');
            $User->setData($data);
            $res = $User->updateDb();


            if($res !== false){
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }else{
            $user = M('User')->find(session('home_uid'));
            $this->assign('one',$user);
            $this->assign('user_menu',$this->getUserMenu());
            $this->display();
        }
    }


    public function upload_img($type=0)
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 2 * 1024 * 1024 ;// 设置附件上传大小 2m
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
        // $upload->savePath = 'Goods/'; // 设置附件上传（子）目录
        $upload->subName = array('date','Y/m/d');
        // 上传文件
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info) {// 上传错误提示错误信息
            $this->ajaxReturn(array("error"=>$upload->getError()));

        }else{ // 上传成功
            $pic_url = 'Uploads/'.$info['savepath'].$info['savename'];
            $image = new \Think\Image();
            $img = $image->open($pic_url);
            $img->thumb(150, 150,3)->save($pic_url);
            $this->ajaxReturn(array('error'=>'0','pic'=>__ROOT__.'/'.$pic_url,'name'=>$info['savename'],'width'=>'80px'));
        }
    }

    /**
     * 修改密码
     */
    public function change_pwd(){
        if(IS_POST){
            $data = I('post.');
            $User = D('User');
            $data['id'] = session('home_uid');
            $User->setData($data);
            $res = $User->updateDb();
            if($res !== false){
                cookie('password',I('post.password'),array('expire'=>3600*7*24,'prefix'=>'home_'));
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }else{
            $this->assign('user_menu',$this->getUserMenu());
            $this->display();
        }
    }

    /**
     * 检测旧密码
     * @param int $pwd
     */
    public function check_pwd($pwd = 0){
        $one = M('User')->find(session('home_uid'));
        if($one){
            if($pwd == $one['password']){
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }else{
            $this->ajaxReturn(0);
        }
    }

    public function confirm_take($id = 0 ){
        if($id < 1){
            $this->error("非法操作");
        }
        $wh['order_id'] = I('post.id');
        $orders = M('order')->where($wh)->select();
        if($orders){
            $res = M('order')->data(array('status'=>5))->where($wh)->save();
            if($res !== false){
                $this->error('确认收货成功',U('already_bought'));
            }else{
                $this->error('确认收货失败，请稍后重试');
            }
        }else{
            $this->error('确认收货失败，请稍后重试');
        }
    }
}